package com.rdzn.mall.portal.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rdzn.mall.base.util.MinioUtil;
import com.rdzn.mall.base.common.Result;
import com.rdzn.mall.center.entity.OmsFile;
import com.rdzn.mall.center.service.IOmsFileService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.oss.OssBootUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * minio文件上传示例
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class MUploadController {
    @Autowired
    private IOmsFileService omsFileService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value="${jeecg.uploadType}")
    private String uploadType;

    /**
     * 文件上传统一方法
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        if(oConvertUtils.isEmpty(bizPath)){
            if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload";
                //result.setMessage("使用阿里云文件上传时，必须添加目录！");
                //result.setSuccess(false);
                //return result;
            }else{
                bizPath = "";
            }
        }
        if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
            //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
            String jeditor = request.getParameter("jeditor");
            if(oConvertUtils.isNotEmpty(jeditor)){
                result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
                result.setSuccess(true);
                return result;
            }else{
//                savePath = this.uploadLocal(file,bizPath);
            }
        }else if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
            String orgName = file.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            String file_url = MinioUtil.upload(file, bizPath);
            //保存文件信息
            OmsFile minioFile = new OmsFile();
            minioFile.setFileName(orgName);
            minioFile.setUrl(file_url);
            omsFileService.save(minioFile);
            return Result.ok(minioFile);
        }else{
            return Result.ok(OssBootUtil.upload(file,bizPath));
        }
        if(oConvertUtils.isNotEmpty(savePath)){
            result.setMessage(savePath);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

//    /**
//     * 上传
//     * @param request
//     */
//    @PostMapping(value = "/upload")
//    public Result<?> uploadMinio(HttpServletRequest request) {
////        Result<?> result = new Result<>();
//        String bizPath = request.getParameter("biz");
//        if(oConvertUtils.isEmpty(bizPath)){
//            bizPath = "";
//        }
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
//        String orgName = file.getOriginalFilename();// 获取文件名
//        orgName = CommonUtils.getFileName(orgName);
//        String file_url =  MinioUtil.upload(file,bizPath);
//        //保存文件信息
//        OmsFile minioFile = new OmsFile();
//        minioFile.setFileName(orgName);
//        minioFile.setUrl(file_url);
//        omsFileService.save(minioFile);
////        result.setMessage(file_url);
////        result.setSuccess(true);
//        return Result.ok(minioFile);
//    }

    /**
     * 预览图片&下载文件
     * 请求地址：http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "minio/view/**")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String bucketName = "";
            String fileName = "";
            response.setContentType("image/jpeg;charset=utf-8");
            if (StringUtils.isNotBlank(imgPath)){
                String[] split = imgPath.split("/");
                bucketName = split[0];
                fileName = split[1];
            }
            inputStream = MinioUtil.getMinioFile(bucketName,fileName);
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            log.error("预览图片失败" + e.getMessage());
            // e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }
}
